<?php

namespace addons\TinyShare\api\modules\v1\controllers;

use Yii;
use yii\base\Model;
use addons\TinyShare\common\models\ShareLike;
use addons\TinyShare\common\models\ShareContent;
use api\controllers\OnAuthController;
use common\helpers\ResultHelper;

/**
 * 点赞
 *
 * Class LikeController
 * @package addons\TinyShare\api\modules\v1\controllers
 * @author jackey <270499458@qq.com>
 */
class LikeController extends OnAuthController
{
	public $modelClass = ShareLike::class;
	
	public function actionCreate()
    {
        $content_id = Yii::$app->request->post('content_id');

        $model = $this->findByContentId($content_id);
		
        if ($model) {
            return ResultHelper::json(422, '请不要重复操作');
        }

        // 开始事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
        	$model=new ShareLike();
            $model->attributes = Yii::$app->request->post();
            $model->member_id = Yii::$app->user->identity->member_id;
            if (!$model->save()) {
                // 返回数据验证失败
                return ResultHelper::json(422, $this->getError($model));
            }

            // 点赞回调
            $this->callBack($model, ShareContent::class, 1);

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            // 返回数据验证失败
            return ResultHelper::json(422, $e->getMessage());
        }

        return $model;
    }
	
	/**
     * 取消点赞
     *
     * @param $id
     * @return bool|mixed
     * @throws \Throwable
     */
    public function actionDelete($id)
    {
        /** @var Collect $model */
        $model = $this->findById($id);
        if (!$model) {
            return ResultHelper::json(422, '获取点赞数据失败');
        }

        // 开始事务
        $transaction = Yii::$app->db->beginTransaction();
        try {

            $model->delete();

            // 回调
            $this->callBack($model, ShareContent::class, -1);

            $transaction->commit();
        } catch (\Exception $e) {
            $transaction->rollBack();
            // 返回数据验证失败
            return ResultHelper::json(422, $e->getMessage());
        }

        return true;
    }

    /**
     * @param $content_id
     * @return Nice|array|\yii\db\ActiveRecord|null
     */
    public function findByContentId($content_id)
    {
        return Yii::$app->tinyShareService->like->findByContentId($content_id, Yii::$app->user->identity->member_id);
    }

    /**
     * @param Nice
     * @return Nice|array|\yii\db\ActiveRecord|null
     */
    public function findById($id)
    {
        return Yii::$app->tinyShareService->like->findById($id, Yii::$app->user->identity->member_id);
    }

    /**
     * @param Nice $model
     * @param $class
     * @param $num
     * @return mixed
     */
    public function callBack($model, $class, $num)
    {
        /** @var Model $class */
        return $class::updateAllCounters(['like' => $num], ['id' => $model->content_id]);
    }
}